package net.hserver.gateway.core.strategy.imp;

import net.hserver.gateway.core.strategy.Chose;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询策略
 *
 * @author hxm
 */
public class PollingStrategy<T> implements Chose<T> {

    private List<T> hosts;
    private static PollingStrategy pollingStrategy;
    private AtomicInteger index = new AtomicInteger(0);

    private PollingStrategy() {
    }

    @Override
    public T choseInfo(String ip) {
        while (true) {
            try {
                if (hosts.size() == 0) {
                    return null;
                }
                if (index.intValue() < hosts.size()) {
                    return hosts.get(index.getAndIncrement());
                } else {
                    index.set(0);
                }
            } catch (Exception e) {
                index.set(0);
            }
        }
    }

    public static <T> PollingStrategy getInstance(List<T> hosts) {
        if (pollingStrategy == null) {
            synchronized (PollingStrategy.class) {
                if (pollingStrategy == null) {
                    pollingStrategy = new PollingStrategy();
                }
            }
        }
        pollingStrategy.hosts = hosts;
        return pollingStrategy;
    }
}
